﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Web;
using Microsoft.VisualBasic.FileIO;
using System.Data;


namespace UpdateMyMedia
    {
    public partial class win_Main:Form
        {

#region -----  Vars  -----
        string xLibConf;
        string xRipDir;
        string xMovieLocal;
        string xMovieRemote;
        DataTable xDT_Movies;
        List<string> xL_MovieDirs;
#endregion

        public win_Main()
            {
            InitializeComponent();

            xL_MovieDirs = new List<string>();

            xIN_IP.Text = UpdateMyMedia.Properties.Settings.Default.ServerIP;
            xIN_YAMJDir.Text = UpdateMyMedia.Properties.Settings.Default.YAMJDir;
            xIN_MediaDir.Text = UpdateMyMedia.Properties.Settings.Default.MediaDir;

            xIN_IP_Leave(null, null);

            LoadRipped();
            }

        private void LoadRipped()
            {
            xDG_Movies.Rows.Clear();

            xRipDir = xIN_MediaDir.Text + @"\Ripped";
            if ( !Directory.Exists(xRipDir) )
                return;

            int xRow;
            string xInfo;
            string xName;
            FileInfo xWFile;

            foreach ( string xFile in Directory.GetFiles(xRipDir, "*.mp4") )
                {
                xWFile = new FileInfo(xFile);
                xInfo = string.Format(@"{0}\{1}", xWFile.Directory, xWFile.Name.Replace(xWFile.Extension, ".nfo"));
                xName = xWFile.Name.Replace(xWFile.Extension, "");

                xRow = xDG_Movies.Rows.Add();
                xDG_Movies["DC_Move", xRow].Value = false;
                xDG_Movies["DC_Rename", xRow].Value = xName;
                xDG_Movies["DC_LocalFile", xRow].Value = xName;
                xDG_Movies["DC_LocalFile", xRow].ToolTipText = xWFile.FullName;

                ((DataGridViewComboBoxCell)xDG_Movies["DC_MoveDir", xRow]).Items.Clear();
                ((DataGridViewComboBoxCell)xDG_Movies["DC_MoveDir", xRow]).Items.AddRange(xL_MovieDirs.ToArray());

                if ( File.Exists(xInfo) )
                    xDG_Movies["DC_IMDBURL", xRow].Value = File.ReadAllText(xInfo);
                }
            }


#region ----- Directory select  -----
        private void xBT_MediaDir_Click(object sender, EventArgs e)
            {
            xFD_Dude.SelectedPath = xIN_MediaDir.Text;

            if ( xFD_Dude.ShowDialog() == DialogResult.Cancel )
                return;

            xIN_MediaDir.Text = xFD_Dude.SelectedPath;

            LoadRipped();
            }

        private void xBT_YAMJDir_Click(object sender, EventArgs e)
            {
            xFD_Dude.SelectedPath = xIN_YAMJDir.Text;

            if ( xFD_Dude.ShowDialog() == DialogResult.Cancel )
                return;

            xIN_YAMJDir.Text = xFD_Dude.SelectedPath;
            }
#endregion


        private void xIN_MediaDir_Leave(object sender, EventArgs e)
            {
            LoadRipped();
            }

        private void xIN_IP_Leave(object sender, EventArgs e)
            {
            if ( xIN_IP.Text == "" )
                return;

            xMovieRemote = string.Format(@"\\{0}\movies", xIN_IP.Text);

            if ( Directory.Exists(xMovieRemote) )
                {
                foreach ( string xPath in Directory.GetDirectories(xMovieRemote) )
                    {
                    DirectoryInfo xDude = new DirectoryInfo(xPath);

                    xL_MovieDirs.Add(xDude.Name);
                    }

                xL_MovieDirs.Sort();
                }
            }

        private void xDG_Movies_CellClick(object sender, DataGridViewCellEventArgs iEvt)
            {
            if ( iEvt.ColumnIndex != 3 )
                return;

            if ( xDG_Movies["DC_Rename", iEvt.RowIndex].Value == null )
                return;

            string xFind = xDG_Movies["DC_Rename", iEvt.RowIndex].Value.ToString();

            xFind = HttpUtility.UrlEncode(xFind);
            xDG_Movies[0, iEvt.RowIndex].Value = true;

            Process.Start("http://www.imdb.com/find?s=all&q=" + xFind);
            }

        private void xBT_Go_Click(object sender, EventArgs e)
            {
            if ( !System.IO.Directory.Exists(xIN_YAMJDir.Text) )
                {
                MessageBox.Show("Honk... YAMJ Dir does not exist");
                return;
                }

            if ( xMovieRemote == null || !Directory.Exists(xMovieRemote) )
                {
                MessageBox.Show("Honk!\n\nServer IP is missing");
                return;
                }

            SetupInterface();
            SaveSettings();

            if ( xTC_Main.SelectedTab == xTP_Movie )
                {
                MoveMovies();

                xPB_Movie.Visible = false;
                }
            else
                {
                Cat_WriteConfigFile();
                Cat_CleanStuff();
                Cat_MakeInfoFiles();
                Cat_MoveInfo();

                xPB_CatMain.Visible = false;
                }

            AbleAll(true);
            }

        private void SaveSettings()
            {
            UpdateMyMedia.Properties.Settings.Default.YAMJDir = xIN_YAMJDir.Text;
            UpdateMyMedia.Properties.Settings.Default.MediaDir = xIN_MediaDir.Text;
            UpdateMyMedia.Properties.Settings.Default.ServerIP = xIN_IP.Text;
            UpdateMyMedia.Properties.Settings.Default.Save();

            ShowProgress();
            }

        private void MoveMovies()
            {
            int xRow;
            string xDir;
            string xDst;
            string xSrc;
            string xInfoURL;
            string xInfoFile;
            FileInfo xFI_Temp;

            for ( xRow = 0; xRow < xDG_Movies.Rows.Count; xRow++ )
                {
                xSrc = xDG_Movies["DC_LocalFile", xRow].Value.ToString();

MessageBox.Show(xSrc);

                if ( xDG_Movies["DC_Rename", xRow].Value == null )
                    {
                    xDst = xDG_Movies["DC_LocalFile", xRow].Value.ToString();
                    }
                else
                    {
                    xDst = xDG_Movies["DC_Rename", xRow].Value.ToString();

MessageBox.Show(xSrc + " - " + xDst);

                    if ( xDst != xSrc )
                        File.Move(string.Format(@"{0}\{1}.mp4", xRipDir, xSrc), string.Format(@"{0}\{1}.mp4", xRipDir, xDst));
                    }

MessageBox.Show(xDst);

                if ( IsEmpty(xDG_Movies["DC_IMDBURL", xRow].Value) )
                    {
                    xInfoFile = null;
                    }
                else
                    {
                    xInfoURL = xDG_Movies["DC_IMDBURL", xRow].Value.ToString();
                    xInfoFile = string.Format(@"{0}\{1}.nfo", xRipDir, xDst);

                    File.WriteAllText(xInfoFile, xInfoURL);
                    }

                if ( xDG_Movies["DC_Move", xRow].Value != null )
                    {
                    xDir = string.Format(@"{0}\{1}", xMovieRemote, xDG_Movies["DC_MoveDir", xRow].Value.ToString());

                    if ( xInfoFile != null && File.Exists(xInfoFile) )
                        {
                        xFI_Temp = new FileInfo(xInfoFile);

                        File.Move(xInfoFile, string.Format(@"{0}\{1}", xDir, xFI_Temp.Name));
                        }

MessageBox.Show(string.Format(@"{0}\{1}", xRipDir, xDst) + " = " + string.Format(@"{0}\{1}", xDir, xDst));

                    FileSystem.MoveFile(string.Format(@"{0}\{1}", xRipDir, xDst), string.Format(@"{0}\{1}", xDir, xDst), UIOption.AllDialogs);
                    }
                }
            }

        private void SetupInterface()
            {
            if ( xTC_Main.SelectedTab == xTP_Info )
                {
                xPB_CatMain.Value = 0;
                xPB_CatMain.Maximum = 10;
                xPB_CatMain.Visible = true;
                }
            else
                {
                xPB_Movie.Value = 0;
                xPB_Movie.Visible = true;
                }

            AbleAll(false);

            ShowProgress();
            }

        private void ShowProgress()
            {
            if ( xTC_Main.SelectedTab == xTP_Info )
                xPB_CatMain.Value++;
            else
                xPB_Movie.Value++;

            Application.DoEvents();
            }

        private void AbleAll(bool iEnable)
            {
            xBT_Go.Enabled = iEnable;
            xIN_IP.Enabled = iEnable;
            xTC_Main.Enabled = iEnable;
            xDG_Movies.Enabled = iEnable;
            xIN_YAMJDir.Enabled = iEnable;
            xTB_Threads.Enabled = iEnable;
            xTB_Threads.Enabled = iEnable;
            xIN_MediaDir.Enabled = iEnable;
            }


#region -----  Movie Category stuff  -----
        private void Cat_WriteConfigFile()
            {
            xLibConf = xIN_YAMJDir.Text + @"\My_Library.xml";

            if ( System.IO.File.Exists(xLibConf) )
                System.IO.File.Delete(xLibConf);

            System.Xml.XmlTextWriter xXW_Conf = new System.Xml.XmlTextWriter(xLibConf, null);

            xXW_Conf.WriteStartElement("libraries");
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteStartElement("library");
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteElementString("path", "\\" + xMovieRemote);
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteElementString("playerpath", "file:///opt/sybhttpd/localhost.drives/NETWORK_SHARE/Movies/");
            xXW_Conf.WriteWhitespace("\n");

            xXW_Conf.WriteStartElement("exclude");
            xXW_Conf.WriteStartAttribute("name");
            xXW_Conf.WriteValue("sample,tmp/,temp/,RECYCLER/,RECYCLE.BIN/");
            xXW_Conf.WriteEndAttribute();
            xXW_Conf.WriteEndElement();
            xXW_Conf.WriteWhitespace("\n");

            xXW_Conf.WriteElementString("description", "");
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteElementString("prebuf", "");
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteElementString("scrapeLibrary", "true");
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteEndElement();
            xXW_Conf.WriteWhitespace("\n");
            xXW_Conf.WriteEndElement();
            xXW_Conf.Close();

            ShowProgress();
            }

        private void Cat_CleanStuff()
            {
            xMovieLocal = string.Format(@"{0}\UMM", xIN_MediaDir.Text);
            if ( Directory.Exists(xMovieLocal) )
                Directory.Delete(xMovieLocal, true);

            ShowProgress();

            Directory.CreateDirectory(xMovieLocal);
            if ( File.Exists(xMovieRemote + @"\index.htm") )
                File.Delete(xMovieRemote + @"\index.htm");

            if ( Directory.Exists(xMovieRemote + @"\Jukebox") )
                Directory.Delete(xMovieRemote + @"\Jukebox", true);

            ShowProgress();
            }

        private void Cat_MakeInfoFiles()
            {
            Directory.SetCurrentDirectory(xIN_YAMJDir.Text);

            Process xP_Movie = new Process();

            xP_Movie.StartInfo.FileName = "java";
            xP_Movie.StartInfo.Arguments = string.Format("-Xms256m -Xmx1024m -classpath .;resources;lib/* com.moviejukebox.MovieJukebox My_Library.xml -o {0} -D mjb.MaxThreadsProcess={1} -D mjb.MaxThreadsDownload={2}", xMovieLocal, xTB_Threads.Value, xTB_Download.Value);
            xP_Movie.StartInfo.ErrorDialog = false;
            xP_Movie.Start();

            xP_Movie.WaitForExit();
            xP_Movie.Close();

            ShowProgress();
            }

        private void Cat_MoveInfo()
            {
            if ( !File.Exists(xMovieLocal + @"\index.htm") )
                {
                MessageBox.Show("WTF! Something went wrong!", "UMM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
                }

            File.Move(xMovieLocal + @"\index.htm", xMovieRemote + @"\index.htm");

            ShowProgress();

            if ( !Directory.Exists(xMovieRemote + @"\Jukebox") )
                Directory.CreateDirectory(xMovieRemote + @"\Jukebox");

            if ( !Directory.Exists(xMovieRemote + @"\Jukebox\pictures") )
                Directory.CreateDirectory(xMovieRemote + @"\Jukebox\pictures");

            string xDst;
            string xSrc;
            string[] xA_Pics = Directory.GetFiles(xMovieRemote + @"\Jukebox\pictures");
            string[] xA_Files = Directory.GetFiles(xMovieLocal + @"\Jukebox");

            ShowProgress();

            xPB_CatFile.Value = 0;
            xPB_CatFile.Maximum = xA_Files.Length + xA_Pics.Length;
            xPB_CatFile.Visible = true;

            foreach ( string xFile in xA_Files )
                {
                xDst = string.Format(@"{0}\Jukebox\{1}", xMovieRemote, Path.GetFileName(xFile));
                xSrc = string.Format(@"{0}\Jukebox\{1}", xMovieLocal, Path.GetFileName(xFile));

                File.Move(xSrc, xDst);

                xPB_CatFile.Value++;

                if ( (xPB_CatFile.Value % 20) == 0 )
                    Application.DoEvents();
                }

            ShowProgress();

            foreach ( string xFile in xA_Pics )
                {
                xDst = string.Format(@"{0}\Jukebox\pictures\{1}", xMovieRemote, Path.GetFileName(xFile));
                xSrc = string.Format(@"{0}\Jukebox\pictures\{1}", xMovieLocal, Path.GetFileName(xFile));

                File.Move(xSrc, xDst);

                xPB_CatFile.Value++;

                if ( (xPB_CatFile.Value % 20) == 0 )
                    Application.DoEvents();
                }

            ShowProgress();

            xPB_CatFile.Visible = false;

            Directory.Delete(xMovieLocal, true);
            }
#endregion

        private bool IsEmpty(object iWhat)
            {
            if ( iWhat == null || iWhat == DBNull.Value )
                return true;

            if ( iWhat.ToString().Trim() == "" )
                return true;

            return false;
            }

        private void xDG_Movies_CellValueChanged(object sender, DataGridViewCellEventArgs e)
            {
            xDG_Movies.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }

        private void xDG_Movies_CurrentCellDirtyStateChanged(object sender, EventArgs e)
            {
            xDG_Movies.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }

        }
    }
